﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AgCIM.Tools.SpatialEncoding.Beidou
{
    public class BeidouEncoder
    {
        /// <summary>
        /// 根据包围盒数据进行编码
        /// </summary>
        /// <param name="minPoint">最小值点{lng:lat:alt}</param>
        /// <param name="maxPoint">最大值点{lng:lat:alt}</param>
        /// <returns></returns>
        public static BeidouCodeInfo Encode(Coordinate minPoint, Coordinate maxPoint)
        {
            BeidouCodeInfo codeInfo = new BeidouCodeInfo();
            var boundingBox = new BeidouBoundingBox(minPoint, maxPoint, true);
            var gridCell = new BeidouGridCellCompute(boundingBox);
            var levelInfo = gridCell.JudgeLodMesh();
            var levelIndex = levelInfo.LevelIndex;

            var elementCenter = boundingBox.GetCenter();
            return Encode(elementCenter, levelIndex);
        }

        /// <summary>
        /// 根据包围盒数据进行编码
        /// </summary>
        /// <param name="minPoint">最小值点{lng:lat:alt}</param>
        /// <param name="maxPoint">最大值点{lng:lat:alt}</param>
        /// <returns></returns>
        public static BeidouCodeInfo Encode(Coordinate minPoint, Coordinate maxPoint, int level)
        {
            BeidouCodeInfo codeInfo = new BeidouCodeInfo();
            var boundingBox = new BeidouBoundingBox(minPoint, maxPoint, true);
            var elementCenter = boundingBox.GetCenter();

            return Encode(elementCenter, level);
        }

        private static BeidouCodeInfo Encode(Cartographic elementCenter, int level)
        {
            BeidouSpatialEncodingPlanarCode beidouSpatialEncodingPlanarCode = new BeidouSpatialEncodingPlanarCode();
            var locationCode = beidouSpatialEncodingPlanarCode.GetPlanarBeidouCode(new double[] { elementCenter.Longitude, elementCenter.Latitude }, level);

            BeidouSpatialEncodingHeightCode beidouSpatialEncodingHeightCode = new BeidouSpatialEncodingHeightCode();
            var heightCode = beidouSpatialEncodingHeightCode.GetFullHeightBeidouCode(elementCenter.Height);
            var finalBeidouCode = new List<string>();
            for (int i = 0; i < locationCode.Count; i++)
            {
                finalBeidouCode.Add(locationCode[i]);
                finalBeidouCode.Add(heightCode.CodeTrans[i]);
            }

            return new BeidouCodeInfo()
            {
                LocationCode = locationCode,
                Level = level,
                HeightCode = heightCode,
                FinalBeidouCode = finalBeidouCode
            };
        }
    }

    public class BeidouCodeInfo
    {
        public List<string> LocationCode { get; set; }

        public int Level { get; set; }

        public HeightCodeObject HeightCode { get; set; }

        public List<string> FinalBeidouCode { get; set; }
    }
}
